App.Api = angular.module('Api', []).
controller('Api.Ctrl', ['Api.Service', 'MainApp.ConfigService', function (Api, Config) {
	note$rez = Config.Api.cleanValue;
}]).
service('Api.Service', 
	['Api.DataGetter', 'Api.Delmem', 'Api.Delnote', 'Api.Delrelnote', 'Api.Delreluser', 'Api.Deluser', 'Api.Err', 'Api.Getmems', 'Api.Getnote', 'Api.Getnotes', 'Api.Getusers', 'Api.Newmem', 'Api.Newnote', 'Api.Newuser', 'Api.Putmemnote', 'Api.Putrelnote', 'Api.Putreluser', 'Api.Updatenote', 
	function (DataGetter, Delmem, Delnote, Delrelnote, Delreluser, Deluser, Err, Getmems, Getnote, Getnotes , Getusers, Newmem, Newnote, Newuser, Putmemnote, Putrelnote, Putreluser, Updatenote) {
	this.getData = function (oper, callback) {
		var dg = new DataGetter();
		dg.setCallback(callback);
		dg.setOperation(oper);
		dg.downloadData();
	}
	this.Delmem = Delmem;
	this.DelNote = Delnote;
	this.Delrelnote = Delrelnote;
	this.Delreluser = Delreluser;
	this.Deluser = Deluser;
	this.Err = Err;
	this.GetMems = Getmems;
	this.GetNote = Getnote;
	this.GetNotes = Getnotes;
	this.GetUsers = Getusers;
	this.NewMem = Newmem;
	this.NewNote = Newnote;
	this.NewUser = Newuser;
	this.Putmemnote = Putmemnote;
	this.Putrelnote = Putrelnote;
	this.PutRelUser = Putreluser;
	this.UpdateNote = Updatenote;
}]).
factory('Api.UrlGen', ['MainApp.ConfigService', function (Config) {
	var prefix = Config.Api.address;
	return function UrlGen (obj) {
		var params = ['js=JSON_CALLBACK', 'format=JavaScript'];
		for(param in obj) {
			params.push(param+'='+obj[param]);
		}
		return prefix+params.join('&');
	}
}]).
factory('Api.ResponseHandler', ['MainApp.ConfigService', function (Config) {
	return function responseHandler (obj) {
		var output = false;
		if(note$rez != Config.Api.cleanValue) {
			output = note$rez;
			note$rez = Config.Api.cleanValue;
		}
		return output;
	}
}]).
factory('Api.DataGetter', ['$http', 'Api.ResponseHandler', 'Api.UrlGen', function ($http, responseHandler, urlGen) {
	return function DataGetter () {
		var that = this,
			operation,
			response,
			callback;
		function setOperation (oper) {
			operation = oper;
		}
		function setCallback (func) {
			callback = func;
		}
		function getData () {
			return response;
		}
		function downloadData () {
			var url = urlGen(operation.toObject());
			$http.jsonp(url).then(handle, handle, handle);
		}
		function handle (s) {
			response = responseHandler(s);
			if(response && response.rez == 'error' && response.nrer == 2) {
				setTimeout(downloadData, 100);
			} else {
				callback(response);
			}
		}
		(function construct () {
			that.setOperation = setOperation;
			that.getData = getData;
			that.downloadData = downloadData;
			that.setCallback = setCallback;
			callback = function () {
				return true;
			}
		})();
	}
}]);